import { ref } from "vue";
import { defineStore } from "pinia";
import { loginService } from "@/apis/user";
import { useRouter } from "vue-router";

export const useUserStore = defineStore(
  "user",
  () => {
    const user = ref(null);
    const router = useRouter();
    const login = async (emp) => {
      const res = await loginService(emp);
      console.log(res.data);

      if (res.code === 200) {
        user.value = res.data;
        // eslint-disable-next-line no-undef
        ElMessage.success("登录成功");
        router.replace("/");
      } else {
        // eslint-disable-next-line no-undef
        ElMessage.error(res.data);
      }
    };
    const exitLogin = () => {
      user.value = null;
      router.push("/login");
    };
    return {
      user,
      login,
      exitLogin,
    };
  },
  {
    persist: true,
  }
);
